﻿using Dapper;
using System;
using BCEntity.Trading.SaleShoppingCart;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Trading.SaleShoppingCart
{
    /// <summary>
    /// 销售购物车
    /// </summary>
    public class SaleShoppingCartData : ISaleShoppingCartData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM saleshoppingcart";
        private const string QUERY = @"SELECT SaleShoppingCartId,SaleGoodsNormId,NormName,NormNamePinyin,NormNo,GoodsDisabled,MainImage,HasBargain,SaleAmount,SaleUnit,SaleCount,CreateTime,HasCreateSaleContract,UserId,SaleGoodsId,SaleGoodsCategoryId,CategoryName,CategoryNamePinyin,GoodsName,GoodsNamePinyin,SKU FROM saleshoppingcart";
        public SaleShoppingCartData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查销售购物车是否存在
        public async Task<bool> Exists(long saleShoppingCartId)
        {
            string sql = string.Format(@"{0} WHERE SaleShoppingCartId=?SaleShoppingCartId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleShoppingCartId", saleShoppingCartId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion 

        #region 检查销售商品是否存在
        public async Task<bool> GoodsExists(long saleGoodsId)
        {
            string sql = string.Format(@"{0} WHERE SaleGoodsId=?SaleGoodsId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsId", saleGoodsId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 检查销售商品规格是否存在
        public async Task<bool> GoodsNormExists(long saleGoodsNormId)
        {
            string sql = string.Format(@"{0} WHERE SaleGoodsNormId=?SaleGoodsNormId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsNormId", saleGoodsNormId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加销售购物车
        public async Task<SaleShoppingCartEntity> Add(SaleShoppingCartEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("saleshoppingcart", new string[] { "SaleGoodsNormId", "NormName", "NormNamePinyin", "NormNo", "MainImage","HasBargain", "SaleAmount",
                "SaleUnit", "SaleCount", "UserId", "SaleGoodsId", "SaleGoodsCategoryId", "CategoryName", "CategoryNamePinyin", "GoodsName",
                "GoodsNamePinyin", "SKU" });
            sql = string.Format("{0} {1} WHERE SaleShoppingCartId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsNormId", entity.SaleGoodsNormId, DbType.Int64, size: 20);
            parameters.Add("?NormName", entity.NormName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?NormNamePinyin", entity.NormNamePinyin?.Trim(), DbType.AnsiString, size: 800);
            parameters.Add("?NormNo", entity.NormNo?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?MainImage", entity.MainImage?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?HasBargain", entity.HasBargain, DbType.Boolean);
            parameters.Add("?SaleAmount", entity.SaleAmount, DbType.Decimal, size: 16);
            parameters.Add("?SaleUnit", entity.SaleUnit?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?SaleCount", entity.SaleCount, DbType.Int32, size: 11);
            parameters.Add("?UserId", entity.UserId, DbType.Int64, size: 20);
            parameters.Add("?SaleGoodsId", entity.SaleGoodsId, DbType.Int64, size: 20);
            parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?CategoryNamePinyin", entity.CategoryNamePinyin?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?GoodsName", entity.GoodsName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?GoodsNamePinyin", entity.GoodsNamePinyin?.Trim(), DbType.AnsiString, size: 400);
            parameters.Add("?SKU", entity.Sku?.Trim(), DbType.AnsiString, size: 50);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleShoppingCartEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改销售购物车
        public async Task<SaleShoppingCartEntity> Update(SaleShoppingCartEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("saleshoppingcart", new string[] { "SaleAmount", "SaleCount"}, new string[] { "SaleShoppingCartId" });
            sql = string.Format("{0} {1} WHERE SaleShoppingCartId=?SaleShoppingCartId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleShoppingCartId", entity.SaleShoppingCartId, DbType.Int64, size: 20);
            parameters.Add("?SaleAmount", entity.SaleAmount, DbType.Decimal, size: 16);
            parameters.Add("?SaleCount", entity.SaleCount, DbType.Int32, size: 11);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleShoppingCartEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 修改销售购物车
        public async Task<bool> UpdateSaleCount(long saleShoppingCartId, int saleCount)
        {
            string sql = SqlCommands.GetUpdateSql("saleshoppingcart", new string[] {  "SaleCount" }, new string[] { "SaleShoppingCartId" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleShoppingCartId", saleShoppingCartId, DbType.Int64, size: 20);
            parameters.Add("?SaleCount", saleCount, DbType.Int32, size: 11);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 删除销售购物车
        public async Task<bool> Delete(long saleShoppingCartId)
        {
            string sql = @"DELETE FROM saleshoppingcart WHERE SaleShoppingCartId=?SaleShoppingCartId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleShoppingCartId", saleShoppingCartId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取销售购物车
        public async Task<SaleShoppingCartEntity> GetEntity(long saleShoppingCartId)
        {
            string sql = string.Format(@"{0} WHERE SaleShoppingCartId=?SaleShoppingCartId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleShoppingCartId", saleShoppingCartId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<SaleShoppingCartEntity>(sql, parameters);
        }
        #endregion

        #region 获取销售购物车列表
        public async Task<IEnumerable<SaleShoppingCartEntity>> GetList(long userId)
        {
            string sql = string.Format(@"{0} WHERE HasCreateSaleContract=0 AND UserId=?UserId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?UserId", userId, DbType.Int64);
            return await this.databaseContext.Slave.QueryAsync<SaleShoppingCartEntity>(sql, parameters);
        }
        #endregion

        #region 获取销售购物车商品数量
        public async Task<int> Count(long userId)
        {
            string sql = @"SELECT COUNT(1) FROM saleshoppingcart WHERE HasCreateSaleContract=0 AND UserId=?UserId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?UserId", userId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync<int>(sql, parameters);
        }
        #endregion

        #region 获取销售购物车分页
        public async Task<(IEnumerable<SaleShoppingCartEntity>, int)> Query(long userId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            wheres.Add("UserId=?UserId");
            parameters.Add("?UserId", userId, DbType.Int64);
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM saleshoppingcart {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<SaleShoppingCartEntity, int>(sql, parameters);
        }
        #endregion

        #region 合计销售商品金额
        public async Task<decimal> SumSaleGoodsAmount(List<long> ids)
        {
            string sql = @"SELECT SUM(SaleAmount*SaleCount) FROM SaleShoppingCart WHERE FIND_IN_SET(SaleShoppingCartId,?Ids)";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?Ids", string.Join(',', ids), DbType.AnsiString);
            return await this.databaseContext.Master.ExecuteScalarAsync<decimal>(sql, parameters);
        }
        #endregion

        #region 修改购物车商品已下架
        public async Task<bool> UpdateSaleGoodsDisabled(long saleGoodsId, bool disable)
        {
            string sql = SqlCommands.GetUpdateSql("saleshoppingcart", new string[] { "GoodsDisabled" }, new string[] { "SaleGoodsId" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsDisabled", disable, DbType.Boolean);
            parameters.Add("?SaleGoodsId", saleGoodsId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<bool> UpdateSaleGoodsDisabled(long saleGoodsId, long saleGoodsNormId, bool disable)
        {
            string sql = SqlCommands.GetUpdateSql("saleshoppingcart", new string[] { "GoodsDisabled" }, new string[] { "SaleGoodsId", "SaleGoodsNormId" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsDisabled", disable, DbType.Boolean);
            parameters.Add("?SaleGoodsId", saleGoodsId, DbType.Int64, size: 20);
            parameters.Add("?SaleGoodsNormId", saleGoodsNormId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

    }
}



